﻿import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text,Checkbox } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './login.scss'

import lbicon from '../mall/images/lbicon.png'
import lbicon2 from '../mall/images/lbicon2.png'

export default class Index extends Component {
  constructor(props) {
    super(props);
   
    this.state = {
      openid:"oXkrN4gSRz8und-ZNj5DEiA3lI-o",
      codes:'',
	  	weblogo:CommonJs.getlogo(),
	  	checkList:0,
	  	phone:0,
	  	wxlogindate:''
    }
  }
  config = {
    navigationBarTitleText:'登录'
  }
  
  componentWillMount () {
	var par =this.$router.params
	var _this=this;
	if(par){
		var cs=par.scene;
		if(cs&&cs.indexOf('shareid')>=0){
			var dateinfo = Taro.getStorageSync('dateinfo')
			if(!dateinfo){
				dateinfo={};
			}
			var arr=cs.split("shareid")
		    dateinfo.introducer = arr[0]
			dateinfo.qid="";
		    Taro.setStorage({key:'dateinfo',data:dateinfo})
		}
	}
  	this.getopenid()
  }
  getopenid(){
  	var _this=this
  	Taro.login({
      success(res) {
        if(res.code){
            _this.setState({
              codes:res.code
            })
            
        }else{
        	
          Taro.showToast({
					  title:'网络异常',
					  icon: 'none',
					  duration: 2000
					})
        }
      }
     })
  }


  getuserinfo(res){
   var _this=this
   if(this.state.checkList==1){
   		Taro.showToast({
			  title:'请先阅读并同意用户协议和隐私条款',
			  icon: 'none',
			  duration: 2000
			})
   	 return false;
   }
	 Taro.setStorage({key:'userinfo',data:res.target.userInfo})
	  if(res.target.iv){
	    var date={
	       encryptedData:res.target.encryptedData,
	       iv:res.target.iv,
	       code:_this.state.codes
	    }
	    this.setState({
        wxlogindate:date,
        phone:1
      })
            
	  }
	  else{
	  	Taro.showToast({
	      title:'用户拒接授权,返回首页中',
	      icon: 'none',
	      duration:2000
	    })
	  	setTimeout(() => {
	  		CommonJs.open('/pages/xijia/grouplist')
	  	},2000)
	  }
  }
  cwxlogin(){
  	var date=this.state.wxlogindate;
  	var dateinfo=Taro.getStorageSync('dateinfo')
	if(!dateinfo){
		dateinfo={};
	}
			 if(dateinfo.introducer){
	    	date.introducer=dateinfo.introducer;
	   }
			 if(dateinfo.counselorId){
	    	date.counselorId=dateinfo.counselorId;
	  }
		var _this=this;
  	CommonJs.ajaxRequest('/wxsmalllogin',date,'GET',function(ret){
	 	 if(ret.code!=300){
	 	 		 if(ret.code==202){
	 	 		 		Taro.showToast({
							  title:ret.msg,
							  icon: 'none',
							  duration: 2000
							})
	 	 		 		_this.getopenid()
	 	 		 		return false;
	 	 		 }
	 	 		 	
		     	 dateinfo.userid=ret.id
		     	 dateinfo.token=ret.token
		     	 Taro.setStorage({key:'dateinfo',data:dateinfo})
		       setTimeout(function(){
		       		if(ret.consultantId<=0){
		       			/*判断是否需要更换顾问 */
			       		if (!dateinfo.qid) {
					        CommonJs.open('/pages/xijia/grouplist')
					       } 
					       else {
					        var date1={
					          clusterId:dateinfo.qid
					        }
					        Taro.showToast({
					          title:'加群中',
					          icon: 'none',
					          duration: 1000
					        })
					        CommonJs.ajaxRequest('/openClusterBindingUser/create',date1,'GET',function(res){
					            _this.$preload({
					                type:1,
					                qid:dateinfo.qid
					            })
					            var urls = ''
					            var par = _this.$router.params
					            // console.log(JSON.stringify(par)+'11111111111111')
					            if (par.shareUid) { 
					              urls = '/pages/activity/activity?scene='+dateinfo.qid+'&shareUid='+par.shareUid
					            } else if (par.activityId) {
					              urls = '/pages/activity/activity?scene='+dateinfo.qid+'&activityId='+par.activityId
					            } else {
					              var goodsid=Taro.getStorageSync('goodsid')
					              if(goodsid&&goodsid!=''){
					              	if(goodsid.indexOf("|||")>=0){
					              		var arr=goodsid.split("|||");
					              		_this.$preload({
												      type:arr[0],
												      malltype:arr[1]
												    })
					              	}
					              	else{
						              	_this.$preload({
												      type:goodsid
												    })
						              }
					              	Taro.setStorage({key:'goodsid',data:''}) 
					              	urls = '/pages/mall/goodsxq'
					              }
					              else{
					              	urls = '/pages/xijia/grouplist'
					              }
					            }
					            //console.log(urls);
					            CommonJs.open(urls)
					          },'noloading')
					       }
					    }
		       		else{
		       			CommonJs.open('/pages/index/changegw?cid='+ret.consultantId+'&qid='+dateinfo.qid)
		       		}
		       },300)
	      }
	    else{
	    	
	    	_this.onload()
	    }
	 })
  }
  nologin(){
  	CommonJs.open('/pages/xijia/grouplist')
  }
  read(){
		CommonJs.openTo('/pages/login/read')
	}
  checkBtn(val){
	  this.setState({
		checkList:val
	  });
  }
  closetc(){
  	this.setState({
    	phone:0
   })
  }
  getPhoneNumber(e) { 
  
    var _this=this;
    if(e.detail.errMsg=='getPhoneNumber:ok'){
	    var date=this.state.wxlogindate;
	    date.encryptedDatamobile=e.detail.encryptedData;
		const accountInfo = Taro.getAccountInfoSync();
		const appid=accountInfo.miniProgram.appId;
	    date.appId=appid
	    this.setState({
        wxlogindate:date,
      },function(){
      	_this.cwxlogin()
      })
    }
    else{
    	//CommonJs.msg('微信登录需要允许获取用户手机号才能进行登录')
	    //_this.getopenid()
		var date=this.state.wxlogindate;
			const accountInfo = Taro.getAccountInfoSync();
			const appid=accountInfo.miniProgram.appId;
			date.appId=appid
			this.setState({
			wxlogindate:date,
		  },function(){
			_this.cwxlogin()
		  })
    }
  }  
  open(url){
    CommonJs.open(url);
  }
  render () {
	  const logo=this.state.weblogo
	  const check = this.state.checkList
	  
    return (
    	
    	<View className='page'>
    		<View className='login-page'> 
    			<Image className='login-logo' mode='widthFix' src={logo}></Image>
    			<View className='login-btn'>
    				<Button className='send-btn' openType="getUserInfo" onGetUserInfo={this.getuserinfo} ><Image className='wx-btn' mode='scaleToFill' src='https://minichat.g2ma.com/kedouimg/dl_wx.png'></Image>微信登录</Button>
    			</View>
				<View className='btn01 login-mobile-btn' onClick={this.open.bind(this,'/pages/login/login_mobile')}>手机号/账号登录</View>
				<View className='login-section'>
					<View className='login-img'>
						<Image className='login-imgs' mode='widthFix' onClick={this.checkBtn.bind(this,1)} style={check==0?'':'display:none'} src={lbicon}></Image>
						<Image className='login-imgs' mode='widthFix' onClick={this.checkBtn.bind(this,0)} style={check==1?'':'display:none'} src={lbicon2}></Image>
						</View>
						<View className='login-text' onClick={this.read.bind(this)}>我已阅读并同意"用户协议和隐私条款"</View>
				  </View>
    			<View className='nologin-btn' onClick={this.nologin.bind(this)}>暂不登录</View>
    		</View>
    		<View className='ptc' style={this.state.phone==1?'':'display:none'}>
        	<View className='ptc-con'>
        		<View className='ptc-tit'>操作提示</View>
        		<View className='ptc-main'>微信登录需要获取您的手机号码</View>
        		<View className='ptc-btn'>
        			<View className='btn-cancle' onClick={this.closetc.bind(this)}>取消</View>
        			<View className='btn-sure' style="padding:0">
        				<Button className='send-btn' openType="getPhoneNumber" onGetPhoneNumber={this.getPhoneNumber}>确定</Button>
        			</View>
        		</View>
        	</View>
				</View>
      </View>
    )
  }
}

